app.controller('UserModalCtrl', function ($scope, $modalInstance, toaster, param, ajax) {

	$scope.submitting = false;
	$scope.param = param;
	if ($scope.param.data == null) {
		$scope.param.data = {};
		$scope.param.data.status = 1;
	}
	$scope.enabled = param.data.status > 0;
	if ($scope.param.type == 'insert') $scope.qr = true;

	$scope.ok = function () {
		if ($scope.param.type == "insert") {
			if ($scope.myForm.$valid) {
				if ($scope.password == undefined || $scope.password == "" || $scope.password.length < 6) {
					toaster.pop('warning', '错误', '密码长度必须大于等于6');
					$scope.submitting = false;
					return;
				}
				if ($scope.newpassword == undefined || $scope.newpassword == "" || $scope.newpassword.length < 6) {
					toaster.pop('warning', '错误', '确认密码长度必须大于等于6');
					$scope.submitting = false;
					return;
				}
				if ($scope.password != $scope.newpassword) {
					toaster.pop('warning', '错误', '两次密码输入不一致');
					$scope.submitting = false;
					return;
				}
				if ($scope.agencyList.selected != undefined) {
					$scope.param.data.agencyId = $scope.agencyList.selected.id;
				}
				$scope.param.data.password = $scope.password;
				$modalInstance.close($scope.param);
			}
		} else if ($scope.param.type == "update") {
			if ($scope.myForm.$valid) {
				if ($scope.password != undefined) {
					if ($scope.password.length < 6 && $scope.password.length > 0) {
						toaster.pop('warning', '错误', '密码长度必须大于等于6');
						$scope.submitting = false;
						return;
					}
					if ($scope.password.length >= 6) {
						$scope.param.data.password = $scope.password;
					}
				}
				if ($scope.agencyList.selected != undefined) {
					$scope.param.data.agencyId = $scope.agencyList.selected.id;
				}
				$scope.param.data.status = $scope.enabled ? 1 : 0;
				$modalInstance.close($scope.param);
			}
		}
	};

	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
		$scope.submitting = false;
	};

	//代售点列表读取
	(function () {
		ajax.call(new Req.GET({
			resource: 'agency/list'
		})).then(function (result) {
			$scope.agencyList = result.result;
			if ($scope.param.data.agencyId > 0) {
				var id = $scope.param.data.agencyId;
				var sel = 0;
				for (var i = 0; i < $scope.agencyList.length; i++) {
					sel++;
					if ($scope.agencyList[i].id == id) {
						break;
					}
				}
				$scope.agencyList.selected = $scope.agencyList[sel - 1];
			}
		}, function () { });
	})();
});